# -*- coding: utf-8 -*-
import time

import pyautogui
from DrissionPage import WebPage

from application.comment.comment import CommentParser
from application.video.video import VideoParser


# 请求函数
def run(page):
    # 请求地址
    url = 'https://www.douyin.com/search/%E8%B4%B7%E6%AC%BE?modal_id=7405596476136557876&type=video'
    # 访问请求地址
    page.get(url=url)
    # 监听评论数据包
    page.listen.start(['aweme/v1/web/comment/list/', 'aweme/v1/web/comment/list/reply/'])
    time.sleep(15)
    # 创建评论解析器
    comment_engine = CommentParser(page)
    # 创建视频解析器
    video_engine = VideoParser(page)
    while True:
        comment_engine.get_comment()
        if not comment_engine.has_more:
            time.sleep(1.5)
            page.wait.doc_loaded()
            video_engine.get_video_url()
            video_engine.get_video_detail()  # 获取视频信息
            author = video_engine.author.replace('|', '').strip()
            comment_engine.save(file_name=f"{author}-{video_engine.modal_id}")  # 保存评论数据
            comment_engine.has_more = True

            next_video()


def next_video():
    all_windows = pyautogui.getAllWindows()
    for window in all_windows:
        if "抖音搜索" in window.title:
            window.activate()
            pyautogui.press('down')


if __name__ == '__main__':
    # 创建页面对象
    page = WebPage()

    # 调用请求函数
    run(page=page)
